<template>
  <div class="goods-form" v-loading.fullscreen.lock="loading">
    <template v-if="goodsForm!==null">
      <div class="goods-form-btns" v-if="hasBtns">
        <el-button v-if="!hasReadonly" size="medium" type="primary" @click="saveGoods">
          <span v-if="type==='add'">新增</span>
          <span v-else>修改</span>
        </el-button>
        <template v-if="type==='approval'">
          <el-button v-if="goodsForm.hasApproval" size="medium" type="primary" @click="approvalGoods">审核通过</el-button>
          <el-button v-if="goodsForm.hasRetreat" size="medium" type="danger" @click="retreatGoods">审核退回</el-button>
        </template>
        <el-button v-else-if="hasSave&&type!=='add'" size="medium" type="primary" @click="toCreateNewGoods">保存为新商品</el-button>
      </div>
      <div class="goods-form-content" :class="{'goods-form-content--nonbtn':!hasBtns}">
        <form-group group-title="基本信息">
          <el-form inline label-width="auto" size="medium">
            <el-form-item label="商品名：">
              <div v-if="hasReadonly" class="goods-input">{{goodsForm.goodsName}}</div>
              <el-input v-else v-model="goodsForm.goodsName" class="goods-input"></el-input>
            </el-form-item>
            <el-form-item label="所属总店：">
              <div class="goods-input">{{goodsForm.branchName}}</div>
            </el-form-item>
            <el-form-item label="所属分店：">
              <div class="goods-input">{{goodsForm.partnerName}}</div>
            </el-form-item>
            <el-form-item label="配送方式：">
              <div v-if="hasReadonly" class="goods-input">{{i18n.getMsg(`goods.goodsDefs.buyMethod.${goodsForm.buyMethod}`)}}</div>
              <el-select v-else v-model="goodsForm.buyMethod" class="goods-input">
                <el-option v-for="item in buyMethodList" :key="item.value" :value="item.value" :label="item.label">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品所属：">
              <div v-if="hasReadonly">{{goodsForm.majorTypeName.join(', ')}}</div>
              <el-select v-else filterable multiple v-model="goodsForm.majorType" style="width:400px">
                <el-option v-for="major in majorTypeList" :key="`major_${major.id}`" :value="major.id" :label="major.name" :disabled="major.disabled">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </form-group>

        <form-group group-title="活动申请">
          <el-form inline label-width="auto" size="medium">
            <el-form-item label="活动类型：">
              <div v-if="hasReadonly" class="goods-input">{{goodsForm.activityTypeName}}</div>
              <el-select v-else filterable v-model="goodsForm.activityTypeId" class="goods-input">
                <el-option v-for="item in activityList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>

            <template v-if="goodsForm.activityTypeId!==''">
              <el-form-item label="开始时间：">
                <div v-if="hasReadonly" class="goods-input">{{$moment(goodsForm.activityStartTime).format('YYYY-MM-DD HH:mm:ss')}}</div>
                <sys-date-time-picker v-else clearable v-model="goodsForm.activityStartTime" class="goods-input" type="hour"></sys-date-time-picker>
              </el-form-item>
              <el-form-item label="结束时间：">
                <div v-if="hasReadonly" class="goods-input">{{$moment(goodsForm.activityEndTime).format('YYYY-MM-DD HH:mm:ss')}}</div>
                <sys-date-time-picker v-else clearable v-model="goodsForm.activityEndTime" class="goods-input" type="hour"></sys-date-time-picker>
              </el-form-item>
            </template>
          </el-form>
          <el-form size="medium" label-position="top" v-if="goodsForm.activityTypeId!==''">
            <el-form-item label="活动理由：">
              <div v-if="hasReadonly" class="activity-remark" v-html="getActivityRemark()"></div>
              <el-input v-else v-model="goodsForm.activityRemark" style="width:100%" type="textarea" :autosize="{minRows:1}" resize="none"
                placeholder="活动理由至少10个字"></el-input>
            </el-form-item>
          </el-form>
        </form-group>

        <form-group group-title="商品描述">
          <rich-editor v-if="hasReadonly" disabled ref="descEditor" v-model="goodsForm.goodsDescription"></rich-editor>
          <div style="height:300px" v-else>
            <rich-editor ref="descEditor" v-model="goodsForm.goodsDescription" :query-value="goodsForm.goodsName"></rich-editor>
          </div>
        </form-group>

        <form-group group-title="商品须知">
          <rich-editor v-if="hasReadonly" disabled ref="tipsEditor" v-model="goodsForm.goodsTips"></rich-editor>
          <div style="height:300px" v-else>
            <rich-editor ref="tipsEditor" v-model="goodsForm.goodsTips" :query-value="goodsForm.goodsName"></rich-editor>
          </div>
        </form-group>

        <form-group group-title="商品图片">
          <imgs-upload v-model="goodsForm.goodsPic" :limit="5" :img-width="100" :img-height="100" :readonly="hasReadonly">
          </imgs-upload>
        </form-group>

        <form-group group-title="商品规格">
          <goods-model :goods-form="goodsForm" :type="type" :is-update-price="isUpdatePrice"></goods-model>
        </form-group>
      </div>
    </template>

    <el-dialog append-to-body v-if="type==='approval'" custom-class="sys-dialog" title="设置活动时间" :close-on-click-modal="false"
      :visible.sync="openDialog" width="400px" top="calc(50vh - 130px)">
      <div style="height:200px;overflow:auto">
        <activity-time-setting v-if="openDialog" :goods="goodsForm" @to-approval="toApprovalGoods"></activity-time-setting>
      </div>
    </el-dialog>

    <el-dialog append-to-body v-if="type==='approval'" custom-class="sys-dialog" title="退回原因" :close-on-click-modal="false" :visible.sync="openReason"
      width="400px" top="calc(50vh - 140px)">
      <div style="height:220px;overflow:auto">
        <retreat-reason v-if="openReason" @ensure="toRetreatGoods"></retreat-reason>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import GoodsForm from 'models/goods/goodsForm';

  import BranchApi from 'services/branchApi';
  import PermissionApi from 'services/permissionApi';
  import GoodsApi from 'services/goodsApi';

  import RichEditor from 'commonComponents/richEditor';
  import ImgsUpload from 'commonComponents/imgsUpload';
  import FormGroup from 'commonComponents/formGroup';
  import SysDateTimePicker from 'commonComponents/sysDateTimePicker';
  import GoodsModel from './goodsModel';
  import ActivityTimeSetting from './activityTimeSetting';
  import RetreatReason from './retreatReason';

  export default {
    props: {
      goods: {
        type: Object,
        default () {
          return null
        }
      },
      type: {
        type: String,
        default: 'add'
      },
      user: {
        type: Object,
        default: () => null
      },
      hasSave: {
        type: Boolean,
        default: false
      },
      isUpdatePrice: {
        type: Boolean,
        default: false
      },
      dropdownOption: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },

    computed: {
      hasBtns() {
        if (this.type !== 'look') {
          return true;
        }

        return this.hasSave;
      },
      hasReadonly() {
        return ['add', 'update'].indexOf(this.type) === -1;
      }
    },

    data() {
      return {
        loading: false,
        partnerLoading: false,
        goodsForm: null,
        partnerList: [],
        majorTypeList: [],
        activityList: [],
        buyMethodList: this.i18n.getDropDown('goods.goodsDefs.buyMethod', ['1', '2']),
        openDialog: false,
        openReason: false
      };
    },

    created() {
      let goodsForm;
      if (this.type === 'add') {
        goodsForm = new GoodsForm(undefined, this.user);
        this.goodsForm = goodsForm;
        this.initData(goodsForm);
        return;
      }

      if (this.type === 'update') {
        goodsForm = _.cloneDeep(this.goods);
      } else {
        goodsForm = this.goods;
      }
      this.initData(goodsForm);
    },

    methods: {
      initData(goodsForm) {
        let promiseList = [];
        let type = this.type;
        if (['add', 'update'].indexOf(type) !== -1) {
          promiseList.push(this.setMajorTypeList(goodsForm), this.setActivityList(goodsForm));
        }

        if (type !== 'add') {
          promiseList.push(this.setGoodsModelList(goodsForm));
        }

        this.loading = true;
        Promise.all(promiseList).then(() => {
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      },

      setMajorTypeList(goodsForm) {
        return GoodsApi.getGoodsMajorType(goodsForm).then(majorTypeList => {
          this.majorTypeList = majorTypeList;
          return majorTypeList;
        });
      },

      setActivityList(goodsForm) {
        let dropdownOption = this.dropdownOption;
        let activityList = dropdownOption.activityList;
        if (activityList !== undefined) {
          this.toSetActivityData(activityList, goodsForm);
          return Promise.resolve(activityList);
        }

        GoodsApi.getActivityDropdown().then(activityList => {
          dropdownOption.activityList = activityList;
          this.toSetActivityData(activityList, goodsForm);
          return activityList;
        });
      },

      toSetActivityData(activityList, goodsForm) {
        let activitys = [];
        if (this.type === 'update') {
          if (goodsForm.activityTypeId === '') {
            this.activityList = [{
              id: '',
              name: '无',
            }];
            return;
          }
        } else {
          activitys = [{
            id: '',
            name: '无',
          }];
        }
        activitys.push(...activityList);

        let activityTypeId = goodsForm.activityTypeId;
        if (activityTypeId !== '') {
          let obj = _.find(activityList, {
            id: activityTypeId
          });
          if (obj === undefined) {
            activitys.push({
              id: activityTypeId,
              name: goodsForm.activityTypeName,
              disabled: true
            });
          }
        }
        this.activityList = activitys;
      },

      setGoodsModelList(goodsForm) {
        if (goodsForm === undefined) {
          goodsForm = this.goodsForm;
        }

        return GoodsApi.getGoodsModelList(goodsForm).then(goodsModelList => {
          goodsForm.resetGoodModelList(goodsModelList);
          if (this.goodsForm === null) {
            this.goodsForm = goodsForm;
          }
          return goodsForm;
        });
      },

      saveGoods() {
        let goodsForm = this.goodsForm;
        let code = goodsForm.checkValid();
        if (code !== '') {
          let msg = this.i18n.getMsg(`goods.goodsDefs.error.${code}`);
          this.$message(msg);
          return;
        }

        if (goodsForm.activityTypeId === '') {
          this.toSaveGoods();
          return;
        }
        this.$confirm('我已确认活动商品信息正确且真实', '确认', {
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        }).then(() => {
          this.toSaveGoods();
        }).catch(() => {});
      },

      toCreateNewGoods() {
        let goodsForm = this.goodsForm;
        let code = goodsForm.checkValid(true);
        if (code !== '') {
          let msg = this.i18n.getMsg(`goods.goodsDefs.error.${code}`);
          this.$message(msg);
          return;
        }

        this.$confirm('保存为新商品，不保存活动申请信息，是否继续保存？', '确认', {
          confirmButtonText: "是",
          cancelButtonText: "否"
        }).then(() => {
          this.toSaveGoods(true);
        }).catch(() => {});
      },

      toSaveGoods(isCreateNew = false) {
        let goodsForm = this.goodsForm;
        let descEditor = this.$refs['descEditor'];
        let tipsEditor = this.$refs['tipsEditor'];
        this.loading = true;
        Promise.all([
          descEditor.getEditorContent(),
          tipsEditor.getEditorContent()
        ]).then(res => {
          goodsForm.goodsDescription = res[0];
          goodsForm.goodsTips = res[1];
          if (isCreateNew) {
            this.createNewGoods(goodsForm);
            return;
          }
          if (this.type === 'add') {
            this.addGoods(goodsForm);
          } else {
            this.updateGoods(goodsForm);
          }
        }).catch(() => {
          this.loading = false;
        });
      },

      createNewGoods(goodsForm) {
        this.loading = true;
        GoodsApi.createNewGoods(goodsForm).then(() => {
          this.loading = false;
          this.$alert('保存为新商品成功', '信息').then(() => {
            this.$emit('save-success');
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      addGoods(goodsForm) {
        this.loading = true;
        GoodsApi.addGoods(goodsForm).then(() => {
          this.loading = false;
          this.$alert('新增商品成功', '信息').then(() => {
            this.$emit('save-success');
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      updateGoods(goodsForm) {
        this.loading = true;
        GoodsApi.updateGoods(goodsForm).then(() => {
          this.loading = false;
          this.$alert('修改商品成功', '信息').then(() => {
            this.$emit('save-success');
          });
        }).catch(() => {
          this.loading = false;
        });
      },

      getActivityRemark() {
        let goodsForm = this.goodsForm;
        if (goodsForm === null) {
          return '';
        }

        let remark = goodsForm.activityRemark;
        return remark;
      },

      approvalGoods() {
        let goods = this.goodsForm;
        let activityTypeId = goods.activityTypeId;
        if (activityTypeId === '') {
          this.toApprovalGoods(goods);
          return;
        }
        this.openDialog = true;
      },

      toApprovalGoods(goods, timeData) {
        this.loading = true;
        GoodsApi.updateGoodsStatus(goods.id, 1, {
          timeData
        }).then(() => {
          this.loading = false;
          this.openDialog = false;
          this.$alert('商品成功审核通过，商品上架', '信息', {
            callback: () => {
              this.$emit('approval-success');
            }
          });
        }).catch(() => {
          this.loading = false
        });
      },

      retreatGoods() {
        this.openReason = true;
      },

      toRetreatGoods(reasonText) {
        let goods = this.goods;
        this.loading = true;
        GoodsApi.updateGoodsStatus(goods.id, 0, {
          reasonText
        }).then(() => {
          this.loading = false;
          this.$alert('商品成功审核退回', '信息', {
            callback: () => {
              this.openReason = false;
              this.$emit('approval-success');
            }
          });
        }).catch(() => {
          this.loading = false
        });
      }
    },

    components: {
      RichEditor,
      ImgsUpload,
      FormGroup,
      SysDateTimePicker,
      GoodsModel,
      ActivityTimeSetting,
      RetreatReason
    }
  };

</script>

<style lang="scss" scoped>
  .goods-form {
    padding: 0 10px 5px;
    height: calc(100% - 5px);
    overflow: auto;

    .goods-form-btns {
      margin-bottom: 10px;
    }

    .goods-form-content {
      height: calc(100% - 46px);
      overflow: auto;

      &.goods-form-content--nonbtn {
        height: 100%;
      }

      .form-group {
        margin-bottom: 10px;
      }

      .el-form-item {
        margin-bottom: 10px;
      }

      .goods-input {
        width: 200px;
      }

      .activity-remark {
        width: 100%;
        line-height: 1.2;
      }
    }
  }

</style>

<style lang="scss">
  .goods-form .goods-form-content .el-form.el-form--label-top .el-form-item .el-form-item__label {
    padding-bottom: 0;
  }

</style>
